package cn.stronglink.assetmanage.business.inventory.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.adapter.InventoryDetailAdapter;
import cn.stronglink.assetmanage.business.patrol.view.PatrolDetailActivity;
import cn.stronglink.assetmanage.business.search.SearchActivity;
import cn.stronglink.assetmanage.business.search.SearchDetailsActivity;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.OrderType;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.SpinnerShowUtil;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;
import cn.stronglink.assetmanage.utils.dao.InventoryDataUtil;
import cn.stronglink.assetmanage.utils.dao.SearchDataUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.inventory.InventoryService;
import cn.stronglink.netrequest.exceptions.BusinessErrorException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 未盘1，正常是3，盘亏4，盘盈5，
 */
public class InventoryDetailActivity extends BaseActivity implements View.OnClickListener,
        onRecyclerListener, View.OnTouchListener, IScanerListener, IRfidListener {

    private Spinner spinner_area;
    private Button btn_inventory_detail_already;
    private Button btn_inventory_detail_wait;
    private Button btn_inventory_detail_out;
    private Button btn_inventory_detail_lose;
    private RecyclerView rv_inventory_Detail_list;
    private TextView tv_inventory_detail_no;
    private TextView tv_inventory_detail_plant_time;
    private TextView tv_inventory_detail_num;

    private Button btn_inventory_detail_scan;
    private Button btn_inventory_detail_rfid;
    private Button btn_inventory_detail_save;
    private Button btn_inventory_detail_upload;
    //传过来的盘点单
    private Inventory inventory;
    //地点列表
    private List<String> areaList = new ArrayList<>();
    //全部盘点资产列表
    private List<InventoryDetail> inventoryDetailList = new ArrayList<>();
    //待盘点资产列表
    private List<InventoryDetail> wait_inventoryDetailList = new ArrayList<>();
    //已盘点资产列表
    private List<InventoryDetail> already_inventoryDetailList = new ArrayList<>();
    //盘盈列表
    private List<InventoryDetail> out_inventoryDetailList = new ArrayList<>();
    //盘亏列表
    private List<InventoryDetail> lose_inventoryDetailList = new ArrayList<>();

    private Map<String, InventoryDetail> wait_inventoryDetailMap = new HashMap<>();
    private Map<String, InventoryDetail> already_inventoryDetailMap = new HashMap<>();
    private Map<String, InventoryDetail> out_inventoryDetailMap = new HashMap<>();
    private Map<String, InventoryDetail> lose_inventoryDetailMap = new HashMap<>();

    private List<Room> roomlist = new ArrayList<>();   //地点列表
    private ArrayAdapter<String> arrayAdapter;   //地点适配器
    private InventoryDetailAdapter inventoryDetailAdapter;
    private LinearLayoutManager layoutManager;
    private int waitNum = 0;    //未盘点的数量
    private int alreadyNum = 0;    //已盘点的数量
    private int outNum = 0;     //盘盈
    private int loseNum = 0;    //盘亏
    private int status = Constants.STATUS_ONE;     //默认为待盘点
    private TimerInfraraedScaner scaner;
    private TimerRfidScaner rfidScaner;
    private float mPosX, mCurPosX;
    private Dialog mCustomProgressDialog;
    private static final String TAG = "InventoryDetailActivity";
    String inventoryId;
    private ExecutorService mExecutorService;
    private Map<String, Boolean> rfidMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory_detail);
        initdata();
        initview();

    }


    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(2);
        refreshAssetList();
        refreshList();
        try {
            // 初始化条码扫描模块
            if (scaner == null) {
                scaner = new TimerInfraraedScaner(InventoryDetailActivity.this);
                scaner.setScanerListener(InventoryDetailActivity.this);
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    private void showProgressDialog() {
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                mCustomProgressDialog = CustomProgressDialog.createLoadingDialog(InventoryDetailActivity.this,
                        "正在启动RFID扫描...");
                mCustomProgressDialog.show();
            }
        };

        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                new Handler().post(runnable);
                Looper.loop();
            }
        }.start();
    }

    private void initview() {
        spinner_area = findViewById(R.id.spinner_inventory_detail_area);
        btn_inventory_detail_already = findViewById(R.id.btn_inventory_detail_already);
        btn_inventory_detail_wait = findViewById(R.id.btn_inventory_detail_wait);
        btn_inventory_detail_lose = findViewById(R.id.btn_inventory_detail_lose);
        btn_inventory_detail_out = findViewById(R.id.btn_inventory_detail_out);
        rv_inventory_Detail_list = findViewById(R.id.inventory_detail_asset_list);

        btn_inventory_detail_scan = findViewById(R.id.btn_inventory_detail_scan);
        btn_inventory_detail_rfid = findViewById(R.id.btn_inventory_detail_rfid);
        btn_inventory_detail_save = findViewById(R.id.btn_inventory_detail_save);
        btn_inventory_detail_upload = findViewById(R.id.btn_inventory_detail_upload);
        tv_inventory_detail_no = findViewById(R.id.tv_inventory_detail_no);
        tv_inventory_detail_num = findViewById(R.id.tv_inventory_detail_num);
        tv_inventory_detail_plant_time = findViewById(R.id.tv_inventory_detail_plant_time);


        //设置适配器
        arrayAdapter = new ArrayAdapter<>(this, R.layout.simple_spinner_item, areaList);
        spinner_area.setAdapter(arrayAdapter);
        spinner_area.setEnabled(false);
        SpinnerShowUtil.setSpinnerItemSelectedByValue(spinner_area, inventory.getRoomName());
        inventoryDetailAdapter = new InventoryDetailAdapter(this, null);
        layoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        rv_inventory_Detail_list.setLayoutManager(layoutManager);
        rv_inventory_Detail_list.setAdapter(inventoryDetailAdapter);

        btn_inventory_detail_wait.setOnClickListener(this);
        btn_inventory_detail_already.setOnClickListener(this);
        btn_inventory_detail_out.setOnClickListener(this);
        btn_inventory_detail_lose.setOnClickListener(this);
        btn_inventory_detail_scan.setOnClickListener(this);
        btn_inventory_detail_rfid.setOnClickListener(this);
        btn_inventory_detail_save.setOnClickListener(this);
        btn_inventory_detail_upload.setOnClickListener(this);
        rv_inventory_Detail_list.setOnTouchListener(this);

        tv_inventory_detail_plant_time.setText(inventory.getExecuteTime());
        tv_inventory_detail_no.setText(inventory.getId_());

        //默认为待盘点选中
        btn_inventory_detail_wait.setClickable(true);
        inventoryDetailAdapter.setListener(this);

        spinner_area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                refreshList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        changeColor(status);

    }

    public void initdata() {
        //获取传过来的inventoryId
        Intent intent = getIntent();
        areaList.add("全部地点");
        if (intent.hasExtra("inventoryDetail")) {
            inventoryId = intent.getStringExtra("inventoryDetail");
            if (inventoryId == null) {
                Toast.makeText(this, "盘点单号为空", Toast.LENGTH_SHORT).show();
                return;
            }
            //获取当前盘点单，地点列表，资产详情
            inventory = InventoryDataUtil.getInventoryByOrderNo(inventoryId);
            String userId = User.getInstance().getId_();
            if (userId != null && !"".equals(userId)) {
                inventory.setUpdateBy(Long.valueOf(userId));
            }
            inventory.setUpdateTime(CheckDataUtil.updateTime());
            roomlist = InventoryDataUtil.getAreaList();
            if (inventory == null || roomlist == null) {
                Toast.makeText(this, "获取盘点单或地点为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (roomlist != null) {
                for (Room room : roomlist) {
                    areaList.add(room.getName());
                }
            }
        }
        mExecutorService = Executors.newFixedThreadPool(10);
    }

    private void refreshAssetList() {
        wait_inventoryDetailList.clear();
        already_inventoryDetailList.clear();
        out_inventoryDetailList.clear();
        lose_inventoryDetailList.clear();
        inventoryDetailList = InventoryDataUtil.getInventoryDetailListByOrderId(inventoryId);
        if (inventoryDetailList != null) {
            for (InventoryDetail inventoryDetail : inventoryDetailList) {
                switch (inventoryDetail.getStatus()) {
                    case Constants.STATUS_ONE:
                        wait_inventoryDetailList.add(inventoryDetail);
                        wait_inventoryDetailMap.put(inventoryDetail.getRfidNo(), inventoryDetail);
                        wait_inventoryDetailMap.put(inventoryDetail.getSerialNo(), inventoryDetail);
                        break;
                    case Constants.STATUS_THREE:
                        already_inventoryDetailList.add(inventoryDetail);
                        already_inventoryDetailMap.put(inventoryDetail.getRfidNo(), inventoryDetail);
                        already_inventoryDetailMap.put(inventoryDetail.getSerialNo(), inventoryDetail);

                        break;
                    case Constants.STATUS_FIVE:
                        out_inventoryDetailList.add(inventoryDetail);
                        out_inventoryDetailMap.put(inventoryDetail.getRfidNo(), inventoryDetail);
                        out_inventoryDetailMap.put(inventoryDetail.getSerialNo(), inventoryDetail);
                        break;
                    case Constants.STATUS_FOUR:
                        lose_inventoryDetailList.add(inventoryDetail);
                        lose_inventoryDetailMap.put(inventoryDetail.getRfidNo(), inventoryDetail);
                        lose_inventoryDetailMap.put(inventoryDetail.getSerialNo(), inventoryDetail);
                        break;
                    default:
                        break;
                }
            }
            waitNum = wait_inventoryDetailList.size();
            alreadyNum = already_inventoryDetailList.size();
            outNum = out_inventoryDetailList.size();
            loseNum = lose_inventoryDetailList.size();
        }
    }

    //改变button的text
    private void changeText() {
        btn_inventory_detail_wait.setText("待盘点(" + waitNum + ")");
        btn_inventory_detail_already.setText("已盘点(" + alreadyNum + ")");
        btn_inventory_detail_out.setText("盘盈(" + outNum + ")");
        btn_inventory_detail_lose.setText("盘亏(" + loseNum + ")");
        tv_inventory_detail_num.setText(waitNum + alreadyNum + outNum + loseNum + "");

    }

    //改变待盘点已盘点颜色
    private void changeColor(int status) {
        switch (status) {
            case Constants.STATUS_ONE:     //wait
                btn_inventory_detail_wait.setBackground(null);
                btn_inventory_detail_wait.setTextColor(getResources().getColor(R.color.blue_inventory_text));
                btn_inventory_detail_already.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_already.setTextColor(Color.BLACK);
                btn_inventory_detail_out.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_out.setTextColor(Color.BLACK);
                btn_inventory_detail_lose.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_lose.setTextColor(Color.BLACK);
                break;
            case Constants.STATUS_THREE:     //already
                btn_inventory_detail_already.setBackground(null);
                btn_inventory_detail_already.setTextColor(getResources().getColor(R.color.blue_inventory_text));
                btn_inventory_detail_wait.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_wait.setTextColor(Color.BLACK);
                btn_inventory_detail_out.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_out.setTextColor(Color.BLACK);
                btn_inventory_detail_lose.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_lose.setTextColor(Color.BLACK);
                break;
            case Constants.STATUS_FIVE:     //out
                btn_inventory_detail_out.setBackground(null);
                btn_inventory_detail_out.setTextColor(getResources().getColor(R.color.blue_inventory_text));
                btn_inventory_detail_wait.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_wait.setTextColor(Color.BLACK);
                btn_inventory_detail_lose.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_lose.setTextColor(Color.BLACK);
                btn_inventory_detail_already.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_already.setTextColor(Color.BLACK);
                break;
            case Constants.STATUS_FOUR:     //lose
                btn_inventory_detail_lose.setBackground(null);
                btn_inventory_detail_lose.setTextColor(getResources().getColor(R.color.blue_inventory_text));
                btn_inventory_detail_wait.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_wait.setTextColor(Color.BLACK);
                btn_inventory_detail_out.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_out.setTextColor(Color.BLACK);
                btn_inventory_detail_already.setBackgroundColor(getResources().getColor(R.color.gray_inventory_btn));
                btn_inventory_detail_already.setTextColor(Color.BLACK);
                break;
            default:
                break;
        }

    }


    //刷新列表
    private void refreshList() {
        waitNum = 0;
        alreadyNum = 0;
        outNum = 0;
        loseNum = 0;
        outNum = out_inventoryDetailList.size();
        waitNum = wait_inventoryDetailList.size();
        alreadyNum = already_inventoryDetailList.size();
        loseNum = lose_inventoryDetailList.size();
        refreshAdapter(wait_inventoryDetailList, already_inventoryDetailList, out_inventoryDetailList, lose_inventoryDetailList, status);
    }

    private void refreshAdapter(List<InventoryDetail> waitlist, List<InventoryDetail> alreadylist, List<InventoryDetail> outlist, List<InventoryDetail> lostlist, int status) {
        inventoryDetailAdapter = new InventoryDetailAdapter(this, null);
        inventoryDetailAdapter.setListener(this);
        rv_inventory_Detail_list.setAdapter(inventoryDetailAdapter);
        switch (status) {
            case Constants.STATUS_ONE:
                inventoryDetailAdapter.notifyDatasChanged(waitlist);
                break;
            case Constants.STATUS_THREE:
                inventoryDetailAdapter.notifyDatasChanged(alreadylist);
                break;
            case Constants.STATUS_FIVE:
                inventoryDetailAdapter.notifyDatasChanged(outlist);
                break;
            case Constants.STATUS_FOUR:
                inventoryDetailAdapter.notifyDatasChanged(lostlist);
                break;
            default:
                break;
        }
        changeText();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_inventory_detail_wait:
                showWaiInventory();
                break;
            case R.id.btn_inventory_detail_already:
                showInventoryed();
                break;
            case R.id.btn_inventory_detail_out:
                showInventoryOut();
                break;
            case R.id.btn_inventory_detail_lose:
                showInventoryLose();
                break;
            case R.id.btn_inventory_detail_scan:
                if (scaner == null) {
                    scaner = new TimerInfraraedScaner(this);
                    scaner.setScanerListener(this);
                }
                try {
                    scaner.playSingle();
                } catch (Exception e) {
                    ToastUtil.toastShort(e.getMessage());
                }

                break;
            case R.id.btn_inventory_detail_rfid:
                switchRfidScan();
                break;
            case R.id.btn_inventory_detail_save:
                try {
                    inventory.setStatus(Constants.STATUS_ONE);
                    inventory.setOperatorName(User.getInstance().getName());
                    //将待盘点资产改为盘亏
                    for (InventoryDetail inventoryDetail : inventoryDetailList) {
                        if (inventoryDetail.getStatus() == Constants.STATUS_ONE) {
                            inventoryDetail.setStatus(Constants.STATUS_FOUR);
                        }
                    }
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    inventory.setUpdateTime(format.format(new Date()));
                    inventory.setExecuteTime(format.format(new Date()));
                    inventory.setDetailList(inventoryDetailList);
                    inventory.setMoreOutList(out_inventoryDetailList);
                    InventoryDataUtil.saveInventory(inventory);
                    ToastUtil.toastShort("盘点状态更改完成");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.btn_inventory_detail_upload:
                showOrderUploadDialog();
                break;
            default:
                break;

        }
    }

    private void showOrderUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否上传单中所有数据，上传成功后，本单中所有数据会删除。");
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                if (inventory != null) {
                    mCustomProgressDialog = CustomProgressDialog.createLoadingDialog(InventoryDetailActivity.this,
                            getString(R.string.is_upload));
                    mCustomProgressDialog.setCancelable(false);
                    mCustomProgressDialog.show();
                    uploadInventoryData();
                }
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void uploadInventoryData() {
        //将待盘点资产改为盘亏
        for (InventoryDetail inventoryDetail : inventoryDetailList) {
            if (inventoryDetail.getStatus() == Constants.STATUS_ONE) {
                inventoryDetail.setStatus(Constants.STATUS_FOUR);
            }
        }
        //已盘和盘亏数据
        inventory.setDetailList(inventoryDetailList);
        //盘盈数据
        inventory.setMoreOutList(out_inventoryDetailList);
        InventoryService inventoryService = new InventoryService();
        Gson gson = new Gson();
        String uploadData = gson.toJson(inventory);
        try {
            inventoryService.uploadInventoryList(gson.toJson(inventory), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.cancel();
                    }
                    ToastUtil.toastShort(e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.cancel();
                    }
                    String json = response.body().string();
                    if (json != null) {
                        Gson gson1 = new Gson();
                        final Result<String> result = gson1.fromJson(json, new TypeToken<Result<String>>() {
                        }.getType());
                        if (result != null && result.getHttpCode() == 200) {
                            // 删除本地单子
                            ToastUtil.toastShort("上传成功");
                            InventoryDataUtil.deleteInventory(inventory);
                        } else {
                            ToastUtil.toastShort(inventory.getId_() + OrderType.INVENTROY + result.getMsg());
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 推送扫到的Rfid到指定列表
     *
     * @param code
     */
    private void pushRfid(final String code) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                String rfid = code.replace("\r", "");
                if (inventoryDetailList == null) {
                    inventoryDetailList = new ArrayList<>();
                }
                //如果再待盘点里
                if (wait_inventoryDetailMap.containsKey(rfid)) {
                    // 如果扫到的rfid在盘点计划里，并且没有在已盘到的资产列表里，就添加信息到已盘到的列表中
                    if (!already_inventoryDetailMap.containsKey(rfid)) {
                        InventoryDetail goods = wait_inventoryDetailMap.get(rfid);
                        wait_inventoryDetailList.remove(goods);
                        wait_inventoryDetailMap.remove(goods.getRfidNo());
                        inventoryDetailList.remove(goods);
                        // 更改资产状态为已盘点
                        goods.setStatus(Constants.STATUS_THREE);
                        inventoryDetailList.add(goods);
                        already_inventoryDetailList.add(goods);
                        // 将新盘到的资产添加到已盘点列表中
                        already_inventoryDetailMap.put(rfid, goods);
                        waitNum = wait_inventoryDetailList.size();
                        alreadyNum = already_inventoryDetailList.size();
                        // 将资产保持到数据
                        DaoManager.getDaoSession(InventoryDetailActivity.this).getInventoryDetailDao().update(goods);
                    } else {
                        showToast("扫描到的数据已盘");
                    }
                } else if (lose_inventoryDetailMap.containsKey(rfid)) {
                    // 如果扫到的rfid在盘点计划里，并且没有在已盘到的资产列表里，就添加信息到已盘到的列表中
                    if (!already_inventoryDetailMap.containsKey(rfid)) {

                        InventoryDetail goods = lose_inventoryDetailMap.get(rfid);
                        lose_inventoryDetailList.remove(goods);
                        lose_inventoryDetailMap.remove(goods.getRfidNo());
                        inventoryDetailList.remove(goods);
                        // 更改资产状态为已盘点
                        goods.setStatus(Constants.STATUS_THREE);
                        inventoryDetailList.add(goods);
                        already_inventoryDetailList.add(goods);
                        // 将新盘到的资产添加到已盘点列表中
                        already_inventoryDetailMap.put(rfid, goods);
                        loseNum = lose_inventoryDetailList.size();
                        alreadyNum = already_inventoryDetailList.size();
                        // 将资产保持到数据
                        DaoManager.getDaoSession(InventoryDetailActivity.this).getInventoryDetailDao().update(goods);
                    } else {
                        showToast("扫描到的数据已盘");
                    }
                } else if (!wait_inventoryDetailMap.containsKey(rfid) && !lose_inventoryDetailMap.containsKey(rfid) && !already_inventoryDetailMap.containsKey(rfid)) {
                    // 如果扫到的rfid不在盘点计划中，并且没在盘盈列表里，就添加到盘盈列表
                    if (!out_inventoryDetailMap.containsKey(rfid)) {
                        // 通过工厂创建盘盈资产实例
                        InventoryDetail goods = InventoryDataUtil.createInventoryProfitGoods(InventoryDetailActivity.this.inventory.getId_(), rfid);

                        // 更改资产状态为盘盈
                        goods.setStatus(Constants.STATUS_FIVE);
                        // 将盘盈资产放到盘盈缓存列表
                        out_inventoryDetailMap.put(rfid, goods);
                        out_inventoryDetailList.add(goods);
                        inventoryDetailList.add(goods);
                        outNum = out_inventoryDetailList.size();
                        // 将资产保持到数据
                        DaoManager.getDaoSession(InventoryDetailActivity.this).getInventoryDetailDao().insert(goods);

                    } else {
                        showToast("扫描到的数据已盘盈");
                    }
                } else if (already_inventoryDetailMap.containsKey(rfid)) {
                    showToast("扫描到的数据已盘");
                } else {
                    showToast("扫描到的数据不在库中");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshList();
                        changeText();
                    }
                });
            }
        });
    }

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.getToast(InventoryDetailActivity.this, msg);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (this.rfidScaner != null) {
                if (rfidScaner.isSearching()) {
                    rfidScaner.StopSearch();
                    btn_inventory_detail_rfid.setBackground(getResources()
                            .getDrawable(R.drawable.bg_button_inventory_detail, null));
                    btn_inventory_detail_rfid.setText("RFID扫描(OK)");
                }
                this.rfidScaner.setRfidListener(null);
                this.rfidScaner.StopSearch();
                this.rfidScaner.Destory();
                this.rfidScaner = null;
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
        try {
            if (this.scaner != null) {
                this.scaner.setScanerListener(this);
                this.scaner.stop();
                this.scaner.destory();
                this.scaner=null;
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mCustomProgressDialog != null) {
                mCustomProgressDialog.cancel();
            }
            rfidMap = new HashMap<>();
            mExecutorService.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启或关闭rfid扫描
     */
    private void switchRfidScan() {
        if (rfidScaner == null) {
            showProgressDialog();
            rfidScaner = new TimerRfidScaner(InventoryDetailActivity.this);
            rfidScaner.setRfidListener(InventoryDetailActivity.this);
            if (mCustomProgressDialog != null) {
                mCustomProgressDialog.cancel();
            }
        }
        if (rfidScaner.isSearching()) {
            rfidScaner.StopSearch();
            btn_inventory_detail_rfid.setBackground(getResources()
                    .getDrawable(R.drawable.bg_button_inventory_detail, null));
            btn_inventory_detail_rfid.setText("RFID扫描(OK)");
        } else {
            rfidScaner.StartSearch();
            btn_inventory_detail_rfid.setBackground(getResources()
                    .getDrawable(R.drawable.bg_button_inventory_detail_enter, null));
            btn_inventory_detail_rfid.setText("停止扫描");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        try {
            // 按下F3按钮进行Rfid扫描器的开关操作
            if (keyCode == 133) {
                this.switchRfidScan();
            }
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                onBackPressed();
            }
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onKeyLongPress(int i, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public boolean onKeyUp(int i, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int i, int i1, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public void onItemClicked(View v, int postion) {
        PrefUtils.putInt(PrefUtils.WHICH_SEARCH_DETAIL, 2, InventoryDetailActivity.this);
        //跳转到资产详情
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (status) {
            case Constants.STATUS_ONE:
                //未盘
                intent.setClass(InventoryDetailActivity.this, InventoryAssetDetailActivity.class);
                bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, wait_inventoryDetailList.get(postion).getId_());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case Constants.STATUS_THREE:
                //已盘
                intent.setClass(InventoryDetailActivity.this, InventoryAssetDetailActivity.class);
                bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, already_inventoryDetailList.get(postion).getId_());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case Constants.STATUS_FOUR:
                //盘亏
                intent.setClass(InventoryDetailActivity.this, InventoryAssetDetailActivity.class);
                bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, lose_inventoryDetailList.get(postion).getId_());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                mCurPosX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                if (mCurPosX - mPosX > 0
                        && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                    //0,1,2,3待盘点，已盘点，盘盈，盘亏
                    if (status != Constants.STATUS_ONE && status == Constants.STATUS_THREE) {
                        //向左滑動，显示待盘点
                        showWaiInventory();
                    } else if (status != Constants.STATUS_THREE && status == Constants.STATUS_FIVE) {
                        //向左滑動，显示已盘点
                        showInventoryed();
                    } else if (status != Constants.STATUS_FIVE && status == Constants.STATUS_FOUR) {
                        //向左滑动，显示盘盈
                        showInventoryOut();
                    }
                    return true;
                } else if (mCurPosX - mPosX < 0
                        && (Math.abs(mCurPosX - mPosX) > Constants.FLUSH_DISTANCE)) {
                    if (status != Constants.STATUS_THREE && status == Constants.STATUS_ONE) {
                        //向右滑动，显示已盘点
                        showInventoryed();
                    } else if (status != Constants.STATUS_FIVE && status == Constants.STATUS_THREE) {
                        //向右滑动，显示盘盈
                        showInventoryOut();
                    } else if (status != Constants.STATUS_FOUR && status == Constants.STATUS_FIVE) {
                        //向右滑动，显示盘亏
                        showInventoryLose();
                    }
                    return true;
                }
                break;
            default:
                break;
        }

        return false;
    }


    private void showWaiInventory() {
        status = Constants.STATUS_ONE;
        refreshList();
        changeColor(status);
    }

    private void showInventoryed() {
        status = Constants.STATUS_THREE;
        refreshList();
        changeColor(status);
    }

    private void showInventoryOut() {
        status = Constants.STATUS_FIVE;
        refreshList();
        changeColor(status);
    }

    private void showInventoryLose() {
        try {
            status = Constants.STATUS_FOUR;
            refreshList();
            changeColor(status);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRfiding(List<TimerRfidScaner.EpcDataBase> data) {
        try {
            if (data != null && data.size() > 0) {
                String rfid = data.get(data.size() - 1).toString().replace(" ", "");
                if (rfidMap.get(rfid) == null || !rfidMap.get(rfid)) {
                    pushRfid(rfid);
                    rfidMap.put(rfid, true);
                } else {
                    ToastUtil.getToast(InventoryDetailActivity.this, "该数据已扫描");
                }
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onSet() {

    }

    @Override
    public void getException(String msg) {

    }

    @Override
    public void onScaning(List<String> data) {
        try {
            if (data != null && data.size() > 0) {
                String rfid = data.get(data.size() - 1).replace(" ", "");
                if (rfidMap.get(rfid) == null || !rfidMap.get(rfid)) {
                    pushRfid(rfid);
                } else {
                    ToastUtil.getToast(InventoryDetailActivity.this, "该数据已扫描");
                }
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }
}
